package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;

import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private RedisTemplate<String,Object> redisTemplate;
@Autowired
private UserInfoService userInfoService;
    @Override
    public void getCode(String phone) {
        String key = RedisConstant.APP_LOGIN_PREFIX+phone;
        Boolean b = redisTemplate.hasKey(key);
        if(b){
            Integer appLoginCodeTtlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            Integer appLoginCodeResendTimeSec = RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC;
            Long expire = redisTemplate.getExpire(key);
            if(appLoginCodeTtlSec-expire<appLoginCodeResendTimeSec){
                throw  new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        String string = stringBuilder.toString();
        System.out.println("string = " + string);
        redisTemplate.opsForValue().set(key,string,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = (String) redisTemplate.opsForValue().get(key);
        if(code == null){
            throw  new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }else if(!code.equals(loginVo.getCode())){
            throw  new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<UserInfo>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(userInfoLambdaQueryWrapper);
        if(userInfo== null){
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setAvatarUrl("http://www.baidu.com/img/bd_logo.png");
            userInfo.setNickname("佚名" + loginVo.getPhone().substring(7));
            userInfoService.save(userInfo);
        }
        if(userInfo.getStatus()==BaseStatus.DISABLE){
            throw  new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }

    @Override
    public UserInfoVo info(String token) {
        Integer id = (Integer) JwtUtil.parseToken(token).get("userId");
        UserInfo userInfo = userInfoService.getById(id);
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
        return  userInfoVo;
    }
}
